const { exec } = require("../db/mysql");
const { SuccessModel, ErrorModel } = require("../model/res");

const getList = (author, keyword) => {
  // 格式 where 1=1 语法拼接 ?a=1&x=y&xxx=xxx;
  let sql = `select * from blogs where 1=1 `;
  if (author) {
    sql += `and author='${author}'`;
  }
  if (keyword) {
    sql += `and title like '%${keyword}%'`;
  }
  sql += `order by createtime desc;`;
  return exec(sql);
};
const getDetail = (id) => {
  const sql = `select * from blogs where id = '${id}'`;
  return exec(sql)
    .then((data) => {
      return data[0];
    })
    .catch((er) => {
      return err;
    });
};
const newBlog = (blogData) => {
  const { title, content, author } = blogData;
  const createtime = Date.now();
  const sql = `insert into blogs (title, content, createtime, author) values ('${title}', '${content}','${createtime}','${author}')`;
  return exec(sql).then((insertData) => {
    return { id: insertData.insertId };
  });
};
const updateBlog = (id, blogData) => {
  const { title, content } = blogData;
  const sql = `update blogs set title='${title}',content='${content}' where id = ${id}`;
  return exec(sql).then((data) => {
    return true;
  });
};
const deleteBlog = (id, author) => {
  const sql = `delete from blogs where id = ${id}&author='${author}'`;
  return exec(sql).then((data) => {
    return true;
  });
};
module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  deleteBlog,
};
